#include "key_manager.h"
#include "../node/node.h"
#include <stack>

OPEN_JLIB_NS


void KeyManager::dispatchDown (Ptr<Node> root, KeyCode key) {
  debug_assert(key > Unknown && key < Max);
  if (_status.tstzs(key))
  _dispatchDown(root.ptr(), key);
}

void KeyManager::dispatchUp (Ptr<Node> root, KeyCode key) {
  debug_assert(key > Unknown && key < Max);
  if (!_status.testc(key))
    _dispatchUp(root.ptr(), key);
}




void KeyManager::_dispatchDown (Node* node, KeyCode key) {
  auto event = &this->_event;
  if (node->isKeyEnabled())
    node->onKeyDown(event);
  node->reorderUpdateChildren();
  auto children = node->updateQueue();
  auto iter = children.begin();
  auto end = children.end();
  for (; iter != end; ++iter)
    this->_dispatchDown(*iter);
}

void KeyManager::_dispatchUp (Node* node, KeyCode key) {
  auto event = &this->_event;
  if (node->isKeybroadEnabled())
    node->onKeyUp(event);
  node->reorderUpdateChildren();
  auto children = node->updateQueue();
  auto iter = children.begin();
  auto end = children.end();
  for (; iter != end; ++iter)
    this->_dispatchUp(*iter);
}


CLOSE_JLIB_NS
